package v1.com.autoresource.service;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import v1.com.autoresource.mapper.TbOrderMapper;
import v1.com.autoresource.model.dao.TbOrder;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @ProjectName: learning
 * @Package: com.autoresource.service
 * @ClassName: OrderService
 * @Description:
 * @Date: 2021/11/3 3:52 下午
 * @Version: 1.0
 */
@Service
public class OrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    private Random random = new Random();

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    private static final String jdbcUrl = "jdbc:mysql://127.0.0.1:3301/trade?allowMultiQueries=true&rewriteBatchedStatements=true&useServerPrepStmts=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf8";


    public List<TbOrder> batchQueryByIds(long id, int size) {
        return tbOrderMapper.batchQueryByIds(id, size);
    }


    public void jdbcInsertOrder() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");

        Connection connection = DriverManager.getConnection(jdbcUrl, "root", "root");

        PreparedStatement preparedStatement = connection.prepareStatement("insert  into tb_order" +
                "(order_no,user_id,shop_id,payment_channel,order_status,create_time,payment_time,order_sn,goods_count,goods_amount,actual_pay_amount,logistics_fee,address_id,delivery_time,completed_time)" +
                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

        //max_allowed_packet 需要设置，不然异常 ==》set global max_allowed_packet = 10 * 1024 * 1024*1024;
        //TbOrder tbOrder = buildTbOrder(Long.valueOf(0)); //
        for (int i = 1; i <= 1000000; i++) {
            //tbOrder.setOrderNo(i + "");
            TbOrder tbOrder = buildTbOrder(Long.valueOf(i));
            //order_no
            preparedStatement.setString(1, tbOrder.getOrderNo());

            // user_id,
            preparedStatement.setLong(2, tbOrder.getUserId());

            // shop_id,
            preparedStatement.setLong(3, tbOrder.getShopId());

            // payment_channel,
            preparedStatement.setInt(4, tbOrder.getPaymentChannel());

            // order_status,
            preparedStatement.setInt(5, tbOrder.getOrderStatus());

            // create_time,
            preparedStatement.setDate(6, new java.sql.Date(tbOrder.getCreateTime().getTime()));

            // payment_time,
            preparedStatement.setDate(7, new java.sql.Date(tbOrder.getPaymentTime().getTime()));

            // order_sn,
            preparedStatement.setString(8, tbOrder.getOrderSn());

            // goods_count,
            preparedStatement.setInt(9, tbOrder.getGoodsCount());

            // goods_amount,
            preparedStatement.setLong(10, tbOrder.getGoodsAmount());

            // actual_pay_amount,
            preparedStatement.setLong(11, tbOrder.getActualPayAmount());

            // logistics_fee,
            preparedStatement.setLong(12, tbOrder.getLogisticsFee());

            // address_id,
            preparedStatement.setLong(13, tbOrder.getAddressId());

            // delivery_time,
            preparedStatement.setDate(14, new java.sql.Date(tbOrder.getDeliveryTime().getTime()));
            // completed_time
            preparedStatement.setDate(15, new java.sql.Date(tbOrder.getCompletedTime().getTime()));
            preparedStatement.addBatch();
            if (i % 100000 == 0) {
                preparedStatement.executeBatch();
                System.out.println("提交了:" + i);
            }
        }
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        OrderService orderService = new OrderService();
        long s1 = System.currentTimeMillis();
        orderService.jdbcInsertOrder();
        long s2 = System.currentTimeMillis();
        System.out.println("cost time=>>" + (s2 - s1));
    }


    public void batchInsertOrder() {
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        TbOrderMapper mapper = sqlSession.getMapper(TbOrderMapper.class);
        for (int i = 1; i <= 1000000; i++) {
            TbOrder tbOrder = buildTbOrder();
            mapper.insertSelective(tbOrder);
            if (i % 100000 == 0) {
                sqlSession.commit();
                sqlSession.clearCache();
                System.out.println("提交了:" + i);
            }
        }

        System.out.println(mapper);

    }

    public void batchInsert() {
        List<TbOrder> orderList = new ArrayList<>();
        for (int i = 1; i <= 1000000; i++) {
            TbOrder tbOrder = buildTbOrder(Long.valueOf(i));
            orderList.add(tbOrder);
            if (i % 100000 == 0) {
                tbOrderMapper.batchInsert(orderList);
                System.out.println("提交了:" + i);
                orderList.clear();
            }
        }
    }


    public void insertOrder() {
        for (int i = 0; i < 1000000; i++) {
            TbOrder tbOrder = buildTbOrder();
            tbOrderMapper.insertSelective(tbOrder);
        }
    }


    private TbOrder buildTbOrder() {
        TbOrder tbOrder = new TbOrder();
        //tbOrder.setOrderNo(UUID.randomUUID().toString());
        tbOrder.setOrderNo(UUID.randomUUID().toString());
        tbOrder.setUserId(Long.valueOf(UUID.randomUUID().toString().hashCode()));
        tbOrder.setShopId(random.nextLong());

        tbOrder.setPaymentChannel(1);
        tbOrder.setOrderStatus(2);
        tbOrder.setCreateTime(new Date());
        tbOrder.setPaymentTime(new Date());
        tbOrder.setOrderSn(UUID.randomUUID().toString());
        tbOrder.setGoodsCount(1);
        tbOrder.setGoodsAmount(100L);
        tbOrder.setActualPayAmount(100L);

        tbOrder.setLogisticsFee(0L);
        tbOrder.setAddressId(random.nextLong());
        tbOrder.setDeliveryTime(new Date());
        tbOrder.setCompletedTime(new Date());
        return tbOrder;
    }

    private TbOrder buildTbOrder(Long i) {
        TbOrder tbOrder = new TbOrder();
        //tbOrder.setOrderNo(UUID.randomUUID().toString());
        tbOrder.setOrderNo(i + "");
        tbOrder.setUserId(i);
        tbOrder.setShopId(random.nextLong());

        tbOrder.setPaymentChannel(1);
        tbOrder.setOrderStatus(2);
        tbOrder.setCreateTime(new Date());
        tbOrder.setPaymentTime(new Date());
        tbOrder.setOrderSn(i + "");
        tbOrder.setGoodsCount(1);
        tbOrder.setGoodsAmount(100L);
        tbOrder.setActualPayAmount(100L);

        tbOrder.setLogisticsFee(0L);
        tbOrder.setAddressId(random.nextLong());
        tbOrder.setDeliveryTime(new Date());
        tbOrder.setCompletedTime(new Date());
        return tbOrder;
    }

}
